﻿# -*- coding: utf-8 -*-
import pyTTS,os,sys,string
import pySonic
import optparse  
import pprint
import traceback
from time import sleep,time
from exceptions import Exception
import pymedia.audio.acodec as acodec
from struct import *

def text_to_wave(tts,text):
    return tts.SpeakToMemory(text)

def print_wave_info(format):
    print "AvgBytesPerSec",format.AvgBytesPerSec
    print "BitsPerSample",format.BitsPerSample
    print "BlockAlign",format.BlockAlign
    print "Channels",format.Channels
    print "ExtraData",format.ExtraData
    print "FormatTag",format.FormatTag
    print "SamplesPerSec",format.SamplesPerSec

def init_tts(rate):
    tts=pyTTS.Create()
    print tts.GetVoiceNames()
    tts.SetVoiceByName(u'MS-Anna-1033-20-DSK')
    tts.SetRate(rate)
    return tts

def Play(src,data,format):
    src.Sound = pySonic.MemorySample(data, format.Channels,format.BitsPerSample,format.SamplesPerSec)
    src.Play()
    while src.IsPlaying():
      sleep(0.1)

def encouder(data,enc):
    frames = enc.encode(data)
    return  frames

def make_lrc_line(time,line):
    string="[%.0f:%.3f] %s"%(time//60,time, line)
    print string
    return string

if __name__ == '__main__':

    parser=optparse.OptionParser()
    parser.add_option("-f", "--file", dest="filename",help="the source text file name", metavar="FILE",default="1.txt")
    parser.add_option("-d", "--destfile", dest="destfile",help="the audio and lrc file name", metavar="FILE",default="1")
    parser.add_option("-r", "--rate",  dest="rate", default=0,help="don't print status messages to stdout")
    parser.add_option("-s", "--sound", action="store_false", dest="verbose", default=True,help="don't print status messages to stdout")
    (options, args) = parser.parse_args()
    print "options",options
    print "args",args
    lines=open(options.filename).readlines()
    tts=init_tts(options.rate)
    w = pySonic.World()
    src = pySonic.Source()

    params= {'id': acodec.getCodecID('mp3'),'bitrate': 32000,'sample_rate': 16000,'ext': 'mp3','channels': 1 }
    enc = acodec.Encoder(params)
    print enc.getParams()
    frames=[]
    sec_len=0
    string=""
    for a in lines:
        bili=0
        if a=='\n':
            string+=make_lrc_line(sec_len,a)
            continue
        try:
            print a
            m=tts.SpeakToMemory(a,pyTTS.tts_purge_before_speak)
            format = m.Format.GetWaveFormatEx()
            #print_wave_info(format)
            data = m.GetData()
            string+=make_lrc_line(sec_len,a)
            sec_len+=(len(data)-32)/format.AvgBytesPerSec
            bili=len(data)
            if len(data)==32:
                continue
            #print (data)
            temp=encouder(data,enc)
        except acodec.ACodecError,e:
            print traceback.format_exc()   
            print 'adsfadsfasdfasdfa'
            continue
        frames+=temp

    f = file(options.destfile+u".mp3",'wb')
    for frame in frames:
        f.write(frame)
    f.close()
    f = file(options.destfile+u".lrc",'wb')
    f.write(string)
    f.close()




